<template>
    <div class="app-content">
        <el-card class="search-card" shadow="never">
            <!-- 搜索部分 -->
            <el-row :gutter="10" class="search-section">
                <el-col :span="7">
                    <el-form-item label="所属租户：">
                        <el-select v-model="searchData.tenantIdList" multiple filterable clearable placeholder="选择租户"
                            style="width: 240px">
                            <el-option v-for="tenant in allDeptInfo" :key="tenant" :label="tenant.tenantName"
                                :value="tenant.tenantId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="所属项目：">
                        <el-select v-model="searchData.projectList" multiple filterable clearable placeholder="选择项目"
                            style="width: 240px">
                            <el-option v-for="project in allProjectInfo" :key="project" :label="project.projectName"
                                :value="project.tenantId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="负责人：">
                        <el-input v-model="searchData.assignedName" placeholder="负责人用户名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态">
                        <el-select v-model="searchData.taskStatus" placeholder="任务状态">
                            <el-option label="未开始" value="0"></el-option>
                            <el-option label="进行中" value="1"></el-option>
                            <el-option label="已完成" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="10" class="search-section2">
                <el-col :span="9">
                    <el-form-item label="创建时间：">
                        <div class="block">
                            <el-date-picker v-model="searchData.createTimeList" type="daterange" unlink-panels
                                range-separator=">>" start-placeholder="开始日期" end-placeholder="结束日期"
                                :shortcuts="shortcuts" />
                        </div>

                    </el-form-item>

                </el-col>
                <el-col :span="5">
                    <el-button type="primary" class="action-button" @click="search" :icon="Search">搜索</el-button>
                    <el-button @click="reset" type="primary" class="action-button" :icon="Refresh">重置</el-button>
                </el-col>
            </el-row>
        </el-card>
        <el-card class="search-card" shadow="never" style="margin-top: 10px;">
            <!-- 操作按钮组 -->
            <!--任务卡片  -->
            <div class="task-container">
                <task-card v-for="task in tasks" :key="task.taskId" :task="task" @edit="handleCardEdit"
                    @delete="handleCardDelete" @evaluate="handleEvaluate" @update:task="updateTask" />
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination class="pagination-fixed" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" :current-page="pagination.currentPage"
                    :page-sizes="[4, 8, 12, 16, 20]" :page-size="pagination.pageSize"
                    layout="total, sizes, prev, pager, next" :total="pagination.totalNum">

                </el-pagination>
            </div>
        </el-card>
        <!-- 对话框 -->
        <el-dialog v-model="dialogVisible" title="Tips" width="600" :before-close="handleClose" @open="onOpen"
            @close="onClose" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
            <el-segmented v-model="segmentValue" :options="menuoOptions" size="large" />

            <template #footer>
                <div class="dialog-footer">
                    <el-button class="action-button" type="info" @click="dialogVisible = false">取消</el-button>
                    <el-button class="action-button" type="primary" @click="update()">
                        确认
                    </el-button>
                </div>
            </template>

            <el-form ref="dialogForm" style="max-width: 600px; margin-left: 30px;" :model="userForm" :rules="rules"
                label-width="auto" class="el-form" status-icon>

                <div v-show="segmentValue === 'basic'">
                    <el-form-item label="所属租户" prop="tenantName" v-show="dialogType == false">
                        <el-input v-model="userForm.tenantName" style="width: 200px;" readonly />
                    </el-form-item>
                    <el-form-item label="用户名" prop="username" required>
                        <el-input v-model="userForm.username" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password" required v-show="dialogType == true">
                        <el-input v-model="userForm.password" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname" required>
                        <el-input v-model="userForm.nickname" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="userForm.gender" style="width: 200px;">
                            <el-radio value="0">女</el-radio>
                            <el-radio value="1">男</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="userForm.phone" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="userForm.remark" style="width: 200px;" />
                    </el-form-item>
                </div>
                <div v-show="segmentValue === 'tenant' && dialogType == true">
                    <el-form-item label="租户" prop="tenantId">
                        <el-card style="width: 350px;border-radius: 8px; margin-top: 10px;" shadow="hover">
                            <el-select v-model="userForm.tenantId" filterable clearable placeholder="选择租户"
                                style="width: 240px">
                                <el-option v-for="tenant in allDeptInfo" :key="tenant" :label="tenant.tenantName"
                                    :value="tenant.tenantId" />
                            </el-select>
                        </el-card>

                    </el-form-item>
                </div>
            </el-form>
        </el-dialog>
		<el-dialog v-model="CostVisible" :show-close="false" width="1500" >
			<h2>{{projectName}}评估操作界面</h2>
			<CostBasicInfoVue v-if="CostVisible"/>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, watch, reactive } from 'vue'
import type { User, UserDTO } from '../../type/User';
import type { PaginationData } from '../../type/PaginationData';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Search, Refresh } from '@element-plus/icons-vue'
import { getAllTenantInfo, findById } from '../../api/Tenant/tenantApi';
import { addUser, updateUser, deleteUser} from '../../api/Tenant/userApi';
import { Tenant } from '../../type/Tenant';

import type { Task, TaskDTO } from '../../type/Task';
import TaskCard from '../../components/costCalculator/TaskCard.vue';
import { Project } from '../../type/Project';
import { getProjectList, findProjectById } from '../../api/Tenant/projectApi';
import { searchTaskInfo } from '../../api/Tenant/taskApi';
import { currentProjectTask, setCurrentProjectTask } from "../../components/costCalculator/Variables/costVariables"
import { getLoginInfo } from "../../api/Tenant/userApi"
import CostBasicInfoVue from './CostBasicInfo.vue';
import { getProjectDetails } from "../../api/Report/projectData"

const CostVisible = ref(false);


const tasks = ref<TaskDTO[]>([]);

// 表格数据
const tableData = ref<User[]>([]);
//查询数据
const searchData = ref({
	taskType:"2",
    assignedName: "",
    projectList: [],
    taskStatus: "",
    createTimeList: [],
    tenantIdList: []
});


//分页
const isSearch = ref(false); // 判断是否为搜索状态
const pagination = ref<PaginationData<User>>({
    currentPage: 1,
    pageSize: 4,
    totalNum: 10,
    isMore: 0,
    totalPage: 0,
    startIndex: 0,
    items: []
});

const verificationData = ref({
	curUserId:'',
	taskType:'2'
});

const projectName = ref();

const getCurUserId = async()=>{
	const res = await getLoginInfo();
	verificationData.value.curUserId = res.userId;
}


//当每页条数发生了变化，调用此函数
const handleSizeChange = async (val: number) => {
    pagination.value.pageSize = val;
    pagination.value.currentPage = 1; // 切换每页条数时重置为第一页
    if (isSearch.value) {
        await search();  // 如果是搜索状态，调用搜索
    } else {
        await getTaskData();  // 否则调用常规获取数据
    }
};
//当前页码发生变化，调用此函数
const handleCurrentChange = async (val: number) => {
    pagination.value.currentPage = val;
    if (isSearch.value) {
        await search();  // 如果是搜索状态，调用搜索
    } else {
        await getTaskData();  // 否则调用常规获取数据
    }
};

// ---------------------
const getTaskData = async () => {
	isSearch.value = false;
	const conditions = ref({
		taskType:"2",
		assignedName: "",
		projectList: [],
		taskStatus: "",
		createTimeList: [],
		tenantIdList: []
	});
    const res = await searchTaskInfo(pagination.value.currentPage, pagination.value.pageSize, conditions.value);
    const data = res;
    // 更新表格数据
    tasks.value = data.items;

    // 更新分页信息
    pagination.value.currentPage = data.currentPage;
    pagination.value.pageSize = data.pageSize;
    pagination.value.totalNum = data.totalNum;
    pagination.value.isMore = data.isMore;
    pagination.value.totalPage = data.totalPage;
    pagination.value.startIndex = data.startIndex;

};
getTaskData();
// 事件处理方法
const handleCardEdit = (task: Task) => {
	
    console.log('编辑任务:', task);
	
};

const handleCardDelete = (task: Task) => {
    console.log('删除任务:', task);
};

const handleEvaluate = async(task: Task) => {
    // console.log('评估任务:', task);
	setCurrentProjectTask(task.projectId, task.taskId);
	console.log(currentProjectTask.projectId);
	const res = await getProjectDetails(currentProjectTask.projectId);
	projectName.value = res.project.projectName;
	CostVisible.value = true;
};

// 更新任务方法
const updateTask = (updatedTask: Task) => {
    const index = tasks.value.findIndex(task => task.taskId === updatedTask.taskId);
    if (index !== -1) {
        tasks.value[index] = updatedTask;
    }
};



const allDeptInfo = ref<Tenant[]>()
const allProjectInfo = ref<Project[]>()

//获取租户数据
const getTenantData = async () => {
    const res = await getAllTenantInfo();
    allDeptInfo.value = res;
}
getTenantData();

//获取项目数据
//如果tenantIdList有值的话，就根据租户id查询项目
const getProjectData = async () => {
    if (searchData.value.tenantIdList.length > 0) {
        const res = await findProjectById(searchData.value.tenantIdList);
        allProjectInfo.value = res;
    } else {
        const res = await getProjectList();
        allProjectInfo.value = res;
    }
}
getProjectData();
//使用 watch 来监听 searchData.tenantIdList 的变化
watch(
    () => searchData.value.tenantIdList,
    () => {
        // 当 tenantIdList 发生变化时，重新获取项目数据
        getProjectData();

    }
);


//日期选择器
const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]


//------------搜索----------------
const search = async () => {
    isSearch.value = true;
    const res = await searchTaskInfo(pagination.value.currentPage, pagination.value.pageSize, searchData.value);

    // 更新表格数据
    tasks.value = res.items;

    // 更新分页信息
    pagination.value.currentPage = res.currentPage;
    pagination.value.pageSize = res.pageSize;
    pagination.value.totalNum = res.totalNum;
    pagination.value.isMore = res.isMore;
    pagination.value.totalPage = res.totalPage;
    pagination.value.startIndex = res.startIndex;
}
const reset = async () => {
    isSearch.value=false;
    searchData.value.assignedName = "";
    searchData.value.taskStatus = "";
    searchData.value.createTimeList = [];
    searchData.value.tenantIdList = [];
    searchData.value.projectList = [];
    await getTaskData();
}




//------------对话框----------------
const dialogVisible = ref(false)
// 在编辑的时候不可以选择租户dialogType:false，新增的时候可以选择租户 dialogType:true
const dialogType = ref(true)
const emit = defineEmits(['dialogUpdated']);
const onOpen = () => {
    emit('dialogUpdated', dialogVisible.value)
}
const onClose = () => {
    emit('dialogUpdated', dialogVisible.value)
}
const dialogTitle = ref('')
const handleClose = (done: () => void) => {
    dialogVisible.value = false
    // 重置验证规则，避免触发验证 需要用setTimeout包裹
    setTimeout(() => {
        dialogForm.value?.clearValidate()
    }, 100)
    done()
}
const segmentValue = ref('basic')

const menuoOptions = [
    {
        label: '基础信息',
        value: 'basic',
    },
    {
        label: '租户信息',
        value: 'tenant',
    }
]
//
const dialogForm = ref<FormInstance>()
const userForm = ref<UserDTO>({})
const rules = reactive<FormRules<UserDTO>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    tenantId: [
        { required: true, message: '请选择租户', trigger: 'blur' },
    ]
});

// 编辑行的处理函数
const handleEdit = async (index: number, row: User) => {
    // 编辑逻辑
    dialogTitle.value = '编辑用户'
    dialogType.value = false
    dialogVisible.value = true

    userForm.value = row
    const tenant = await findById(row.tenantId || "");
    if (tenant) {
        userForm.value.tenantName = tenant.tenantName;
        console.log('tenant', tenant)
    }

};
const update = async () => {
    // 更新逻辑
    try {
        const valid = await dialogForm.value?.validate();
        if (valid) {
            if (dialogType.value === false) {
                // 更新逻辑
                const res = await updateUser(userForm.value);
                ElMessage.success('更新成功');
            } else {
                // 新增逻辑
                // 验证租户是否选择
                if (!userForm.value.tenantId) {
                    ElMessage.error('请选择租户');
                    return;
                }
                const res = await addUser(userForm.value);
                await getTaskData();
                ElMessage.success('新增成功');
            }

        } else {
            // 验证失败的情况下，显示错误信息
            ElMessage.error('请检查输入项');
        }
    } catch (error) {
        // 捕获验证失败时的错误
        ElMessage.error('验证失败，请检查输入项');

    }
}

// 删除行的处理函数
const handleRowDelete = (index: number, row: User) => {

    ElMessageBox.confirm(`确定删除 ${row.username} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            tableData.value.splice(index, 1);
            deleteUser(row)
            ElMessage.success('删除成功');
            await getTaskData();
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
};

</script>
<style lang="scss" scoped>
@use "sass:color";
$primary-color: #6067eb;
$info-color: #dadcf6;
$button-border-radius: 4px;
$button-padding: 0.5rem 1rem;
$button-font-size: 16px;
$color-hover: color.adjust($primary-color, $lightness: -10%); // 悬浮时的颜色
$color-disabled: color.adjust($primary-color, $lightness: 15%); // 禁用时的颜色
$info-color-hover: color.adjust($info-color, $lightness: -25%); // 悬浮时的颜色

/* 定义一个 mixin 用于公共按钮样式 */
@mixin action-button-style {
    border-radius: $button-border-radius;
    padding: $button-padding;
    font-size: $button-font-size;
    cursor: pointer;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;

    /* 覆盖 Element Plus 的 primary 按钮样式 */
    &.el-button--primary {
        background-color: $primary-color;
        border-color: $primary-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $color-hover;
            border-color: $color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    &.el-button--info {
        background-color: $info-color;
        border-color: $info-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $info-color-hover;
            border-color: $info-color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    /* 禁用状态下的样式（针对所有类型的按钮） */
    &:disabled,
    &.is-disabled {
        background-color: $color-disabled;
        border-color: $color-disabled;
        color: #fff;
        cursor: not-allowed;
        opacity: 1; // 覆盖 Element Plus 默认的透明度
    }


}

.action-button {
    @include action-button-style;
}

/* 按钮组样式 */
.button-group {
    display: flex;
    gap: 1rem;
    margin-bottom: 10px;
}

.table-button {
    color: #7e63cd;
    font-size: 14px;
    /* 设置你想要的字体大小 */
    font-weight: bold;
    /* 设置字体加粗 */
}


.search-card {
    border-radius: 10px;

    .block {
        padding: 0px 0;
        text-align: center;
        border-right: solid 1px var(--el-border-color);
        flex: 1;
    }

    .block:last-child {
        border-right: none;
    }

}


.pagination-container {
    display: flex;
    margin-top: 25px;
    justify-content: right;
    width: 100%;
    z-index: 1000;
}

.el-segmented {
    --el-segmented-item-selected-color: var(--el-text-color-primary);
    --el-segmented-item-selected-bg-color: #868cf4;
    --el-border-radius-base: 8px;
    --el-text-color-primary: #fff;
    --el-segmented-item-hover-bg-color: #b2b5f0;
    display: flex;
    justify-content: flex-start;
    /* 左对齐 */
    width: 300px;
    margin-bottom: 20px;
}

.task-container {
    display: flex;
    flex-wrap: wrap;
    gap: 60px;
    /* 两列之间的间距，可根据需要调整 */
    //justify-content: space-between;
}
</style>